package com.isyscore.os.metadata.kettle.base;

import com.alibaba.fastjson.JSONObject;
import com.isyscore.os.metadata.enums.DataSourceTypeEnum;
import com.isyscore.os.metadata.enums.KettleDataSourceType;
import org.pentaho.di.core.database.DatabaseMeta;
import org.pentaho.di.core.database.GenericDatabaseMeta;

public class DatabaseCodec {
	
	public static JSONObject encode(DatabaseMeta databaseMeta) {
		
		return null;
	}
	
	public static DatabaseMeta decode(FlowConnection connection){
		DatabaseMeta databaseMeta = new DatabaseMeta();

		databaseMeta.setName(connection.getId() +"-"+connection.getDatabase());
		databaseMeta.setDisplayName(databaseMeta.getName());

		if (KettleDataSourceType.DM.getName().equals(connection.getType())) {
			databaseMeta.setDatabaseType(KettleDataSourceType.GENERIC.getName());
			databaseMeta.getAttributes().put( GenericDatabaseMeta.ATRRIBUTE_CUSTOM_URL, String.format(DataSourceTypeEnum.DM.getUrl(), connection.getServer(), connection.getPort(), connection.getDatabase()));
			databaseMeta.getAttributes().put( GenericDatabaseMeta.ATRRIBUTE_CUSTOM_DRIVER_CLASS, DataSourceTypeEnum.DM.getDriverClass());
		}else{
			databaseMeta.setDatabaseType(connection.getType());
		}
		databaseMeta.setAccessType(DatabaseMeta.TYPE_ACCESS_NATIVE); //使用默认的NATIVE 方式
		databaseMeta.setPassword(connection.getPassword());
		databaseMeta.setDBName(connection.getDatabase());
		databaseMeta.setDBPort(connection.getPort());
		databaseMeta.setHostname(connection.getServer());
		databaseMeta.setUsername(connection.getUsername());

		//将所有字段进行转译，防止数据表上加了区分大小写的问题。
		databaseMeta.setQuoteAllFields(true);

		if(KettleDataSourceType.ORACLE.getName().equals(connection.getType())){
			if("SID".equals(connection.getBasicType())){
				databaseMeta.setDBName(connection.getBasicValue());
			}else{
				databaseMeta.setDBName("/"+connection.getBasicValue());
			}
		}

		if(KettleDataSourceType.SQLSERVER.getName().equals(connection.getType())||KettleDataSourceType.PGSQL.getName().equals(connection.getType())){
			if(connection.getDatabase().contains(".")){
				databaseMeta.setDBName(connection.getDatabase().split("\\.")[0]);
			}
		}

		return databaseMeta;
	}
	
}
